<template>
    <div class="form-page">
        <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
      >
        <el-form-item prop="identifier">
          <el-input v-model="form.identifier" placeholder="用户名/邮箱"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" placeholder="密码"/>
        </el-form-item>
        <el-form-item>
          <AsyncButton class="submit-btn" :loading="loading" type="primary" @click="submitForm(formRef)">
            登录
          </AsyncButton>
        </el-form-item>
        <el-row justify="space-between" :gutter="1">
            <el-col :sm="7" :xs="8">
                <router-link to="register"><el-button link>注册</el-button></router-link>
            </el-col>
            <el-col :sm="7" :xs="8">
                <router-link to="register"><el-button link>忘记密码</el-button></router-link>
            </el-col>
        </el-row>
      </el-form>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { login } from '@/api/index'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store'
import { useRouter, useRoute } from 'vue-router'

const userStore = useUserStore()

const router = useRouter()

const route = useRoute()

const form = ref({
    identifier: '',
    password: '',
});

const rules = {
    identifier: [
        { required: true, message: '请输入用户名/邮箱' },
    ],
    password: [
        { required: true, message: '请输入密码' },
    ],
}

const formRef = ref(null);

const loading = ref(false)

function submitForm(formRef){
    formRef.validate(valid => {
        if(valid){
            loading.value = true
            login(form.value).then(res => {
                console.log(res, 'res')
                loading.value = false
                if(res.code === 200){
                    userStore.updateToken(res.data)
                    router.push('/dashboard')
                }else{
                    ElMessage.error(res.msg)
                }
            }).catch(err => {
                loading.value = false
            })
        }
    });
}

onMounted(() => {
    if(route.query.identifier){
        form.value.identifier = route.query.identifier
    }
})
</script>

<style lang="scss">
@import '@/assets/css/form-page.scss';
</style>